import { Injectable } from '@angular/core';
//原生插
import { SQLite, SQLiteObject,SQLiteTransaction } from '@ionic-native/sqlite/ngx';

//自定义服务
import { NativeService } from "./native.service";
import { SQLITE } from './constants';


/**
 * SQLite数据库
 * @export
 * @class SQLService
 */
@Injectable({
  providedIn: 'root'
})
export class SQLService {

  //window对象
  private win: any = window;
  //数据库对象
  private database: SQLiteObject;
  //是否android环境
  private isAndroid: boolean;

  constructor(private sqlite:SQLite, private nativeService:NativeService) {

    this.isAndroid = this.nativeService.isAndroid();
  }


  /**
   * 自动判断环境创建sqlite数据库
   * @memberof SQLService
   */
  public initDB()
  {
    if (!this.win.sqlitePlugin)
    {
      //window.openDatabase("数据库名字", "版本","数据库描述",数据库大小);
      this.database = this.win.openDatabase(SQLITE.WINDOW.name, SQLITE.WINDOW.version,
        SQLITE.WINDOW.describe, SQLITE.WINDOW.maxSize);
      return;
    }
    if (this.isAndroid)
    {
      this.sqlite.create({
        name: SQLITE.ANDROID.name,
        location: SQLITE.ANDROID.location
      }).then((db) => {
        this.database = db;
      }).catch(err => {
        console.log(err);
      });
    }
    else
    {
      this.sqlite.create({
        name: SQLITE.IOS.name,
        iosDatabaseLocation: SQLITE.IOS.iosDatabaseLocation,
      }).then((db) => {
        this.database = db;
      }).catch(err => {
        console.log(err);
      });
    }
  }


  /**
   * 执行sql语句
   * @param {string} sql
   * @param {*} [params={}]
   * @returns {Promise<any>}
   * @memberof SQLService
   */
  executeSql(sql: string, params: any = []): Promise<any>
  {
    return new Promise((resolve, reject) => {
      try
      {
        this.database.transaction((tx: SQLiteTransaction) => {
          tx.executeSql(sql, params, (tx, res) => {
            resolve({tx, res});
          }, (tx, err) => {
            reject({tx, err});
          });
        });
      }
      catch (err)
      {
        reject({err});
      }
    });
  }

}